import { ImageFormat } from './type';

/**
 * 后缀名映射
 */
export const extMap: Record<ImageFormat, string> = {
	jpg: 'image/jpeg',
	png: 'image/png',
	webp: 'image/webp',
};

/**
 * File 转 base64
 */
export function fileToBase64(file: File): Promise<string> {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result as string);
		reader.onerror = reject;
	});
}

// 可以选择的图片类型
const accept = [
	'jpg',
	'jpeg',
	'png',
	'svg',
	'svgz',
	'webp',
	'ico',
	'xbm',
	'tif',
	'jfif',
	'tiff',
	'bmp',
	'pjp',
	'apng',
	'pjpeg',
	'avif',
];

/**
 * 选择图片
 */
export function selectImage(component?: any) {
	return new Promise<File | undefined>((resolve) => {
		const input = document.createElement('input');
		input.type = 'file';
		input.accept = accept.map((v) => '.' + v).join(',');
		input.onchange = () => {
			const files = input.files;
			if (files && files.length > 0) {
				if (component) {
					// 传入了组件实例直接注入数据
					component?.inject(files[0]);
				}

				resolve(files[0]);
			} else {
				resolve(void 0);
			}
			input.remove();
		};
		input.click();
	});
}

// 匹配数字
const numberRegExp = /^[0-9]$/;

/**
 * 格式化 css 长度
 */
export function formatCSSLength(value: string | number) {
	if (typeof value === 'number') return value + 'px';

	if (numberRegExp.test(value)) return value + 'px';

	return value;
}
